const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const morgan = require('morgan');
require('dotenv').config();
const { Logger } = require('./utils/logger');
const contractsRouter = require('./routes/contracts');

const app = express();
const PORT = process.env.PORT || 8899;

// 中间件
app.use(helmet());
app.use(compression());
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('combined'));

// Swagger文档路由 - 添加错误处理
try {
  const { swaggerUi, specs } = require('./config/swagger');
  
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs, {
    explorer: true,
    customCss: '.swagger-ui .topbar { display: none }',
    customSiteTitle: 'HT Service API Documentation'
  }));
  
  console.log('✅ Swagger文档路由配置成功');
} catch (error) {
  console.error('❌ Swagger配置失败:', error.message);
  
  // 提供一个简单的API文档页面
  app.get('/api-docs', (req, res) => {
    res.json({
      error: 'Swagger文档配置失败',
      message: error.message,
      availableEndpoints: {
        users: '/api/users',
        auth: '/api/auth',
        documents: '/api/documents' // 新增
      }
    });
  });
}

// 根路由
app.get('/', (req, res) => {
  res.json({
    message: '欢迎使用HT Service API',
    version: '1.0.0',
    documentation: '/api-docs',
    endpoints: {
      users: '/api/users',
      auth: '/api/auth',
      documents: '/api/documents' // 新增
    }
  });
});

// 路由 - 同时支持复数和单数形式
app.use(['/api/users', '/api/user'], require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/documents', require('./routes/documents')); // 新增
app.use('/api/payments', require('./routes/payments')); // 支付路由
app.use('/api/contracts', contractsRouter);

// 404处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.path
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error('❌ [全局错误]:', {
    error: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
    timestamp: new Date().toISOString()
  });
  
  Logger.logRequest(req, res, err);
  
  res.status(err.status || 500).json({
    success: false,
    message: process.env.NODE_ENV === 'development' ? err.message : '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.stack : undefined
  });
});

// 启动服务器
app.listen(PORT, '0.0.0.0', () => {
  console.log(`🚀 服务器启动成功 - http://localhost:${PORT}`);
  console.log(`📚 API文档地址 - http://localhost:${PORT}/api-docs`);
  
  Logger.logInfo('服务器启动', {
    port: PORT,
    env: process.env.NODE_ENV || 'development'
  });
});

module.exports = app;